
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
let interval; 

Page({
  data: {
    Sender:'',
    Time:'',
    recipient: '',
    textContent: '',
    recipient:'',
    textContent:'',
    activeIndex: 0 ,
    moreVisible:false,
    previewWord:true,
    allVisible:false,
    previewAll: false, 
    imageList: [],
    videoList: [],
    time: 0,
    duration: 600000,
    tempFilePath: "",
    status: 0,
    playStatus: 0,
    showRecordingLayout: false,  
    showRecordingBar: false,
    isPlaying: false,
    recordingData: {
      filePath: '' 
    },
    audioPath: ''           
  },

  updateRecipient(e) {
    this.setData({
      recipient: e.detail.value
    });
  },

  updateSender(e) {
    this.setData({
      Sender: e.detail.value
    });
  },

  updateTextData(event) {
    this.setData({
      textContent: event.detail.value
    });
  },

  updateTime(e) {
    this.setData({
      Time: e.detail.value
    });
  },

  onInputName(e) {
    this.setData({
      Sender: e.detail.value
    });
  },
  switchTab: function(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      activeIndex: index
    });
  },
  preview:function(){
    this.setData({
      moreVisible:true
    })
  },
  back:function(){
    this.setData({
      moreVisible:false
    })
  },
  previewAll:function(){
    this.setData({
      previewWord:!this.data.previewWord,
      previewAll: !this.data.previewAll 
    })
  },
 
  onLoad(options) {
    const now = new Date();
    const Time = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} `;
    this.setData({ Time });
    this.setData({
      Time: Time
    });

    this.onDataLoad();
  },

  onDataLoad:function()
  {
    let _this = this;
    wx.request({
      url: 'http://localhost:8080/drafts/send',
      method:'GET',
      header:{
        "openid":wx.getStorageSync('openId')
      },
      success(res){

        if(res.data.code === 200)
        {
          const data = res.data.data;
          console.log(data)
          console.log(res.data.data)
          _this.setData({
            id:data.id,
            recipient:data.toName,
            Sender: data.userName,
            textContent:data.content,
            Time:data.date,
            imageList:data.pictureCcs,
            videoList:data.videoCcs
          })
        }
       
      },
      fail(err)
      {
        console.log(err)
      }
    })
  },

  onInputRecipient:function(e)
  {
    console.log(e.detail.value)
    this.setData({
      recipient:e.detail.value
    })
  },
  onInputContent:function(e)
  {
    console.log(e.detail.value)
    this.setData({
      textContent:e.detail.value
    })
  },
  onInputSender:function(e)
  {
    console.log(e.detail.value)
    this.setData({
      Sender:e.detail.value
    })
  },
  onInputTime:function(e)
  {
    this.setData({
      Time:e.detail.value
    })
  },

  
  getPhoto:function()
  {
    let _this = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths;
        const imageNew = _this.data.imageList.concat(tempFilePaths)
        this.setData({
          imageList: imageNew,
          allVisible: true  
          })

        //将图片发送到后端
      }
    });

  },

  getVideo:function()
  {
    let _this = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      success: (res) =>{
        const tempFilePath = res.tempFilePath
        // 根据视频文件进行相关操作
        //将视频传到后端
        console.log(tempFilePath)
        const videoNew = _this.data.videoList.concat(tempFilePath)
        this.setData({
          videoList: videoNew,
          allVisible: true  
          })


      }
    })
  },

  groupImages(imagePaths) {
    const imageList1 = []
    for (let i = 0; i < imagePaths.length; i += 3) {
      imageList1.push(imagePaths.slice(i, i + 3))
    }
    return imageList1
  },
  deleteImage(event) {
    const index = event.currentTarget.dataset.index;
    const newImageList = [...this.data.imageList];
    newImageList.splice(index, 1);
    this.setData({
      imageList: newImageList
    });
  },

  deleteVideo(event) {
    const index = event.currentTarget.dataset.index;
    const newImageList = [...this.data.videoList];
    newImageList.splice(index, 1);
    this.setData({
      videoList: newImageList
    });
  },

  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  save:function()
  {

  },
  drafts:function()
  {
    const url = 'http://localhost:8080/drafts/'
    this.substance(url);
    this.updateImages(url)
    this.updateVideo(url)
  },

  substance:function(url)
  {
    wx.request({
      url: url+'save',
      method:'POST',
      data: {
        toName:this.data.recipient,
        userName: this.data.Sender,
        content:this.data.textContent,
        formatter:this.data.Time
      },
      header:{
        'openid':wx.getStorageSync('openId'),
        'qrcode':wx.getStorageSync('qrcpde')
      },
      success(uploadRes){
        console.log("数据上传成功")
      },
      fail(error)
      {
        console.log("上传失败:",error)
      }

    })
  },
  

  save() {
    const {
      imageList, 
      videoList, 
      audioPath,
      textContent, 
      recipient, 
      Sender, 
      Time 
    } = this.data;

    wx.navigateTo({
      url: '/pages/show/show?images=' + JSON.stringify(imageList) +
           '&videos=' + JSON.stringify(videoList) +
           '&audio=' + audioPath +
           '&text=' + encodeURIComponent(textContent) +
           '&recipient=' + recipient +
           '&Sender=' + Sender +
           '&Time=' + Time
    });
  },


  updateImages:function(url)
  {
    if(this.data.imageList.length != 0)
    {

      this.data.imageList.forEach(function (filePath) {
        wx.uploadFile({
        url: url+'receivesPictures',
          filePath: filePath,
          name: 'images',
          header: {
            'openid':wx.getStorageSync('openId'),
            'qrcode':wx.getStorageSync('qrcpde')
          },
          success: function (res) {
            console.log(res.msg)
          }
        })
      })
    }
  },

  updateVideo:function(url)
  {
    if(this.data.videoList.length != 0)
    {
      this.data.videoList.forEach(function (filePath) {
        wx.uploadFile({
          url: url+'receiveVideos',
          filePath: filePath,
          name: 'videos',
          header: {
            'openid':wx.getStorageSync('openId'),
            'qrcode':wx.getStorageSync('qrcpde')
            },
          success(uploadRes) {
            console.log(uploadRes.data);
          },
          fail(error) {
            console.error('上传失败:', error);
          }
        })
      })
    }
  },

  uploadAudioFile(filePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: '',
        filePath: filePath,
        name: 'audio',
        success(res) {
          const data = JSON.parse(res.data);
          if (res.statusCode === 200 && data.url) {
            resolve(data.url);
          } else {
            reject(new Error('上传失败'));
          }
        },
        fail(err) {
          reject(err);
        }
      });
    });
  },
  
  togglePlayRecording:function() {
    innerAudioContext.src = this.data.recordingData.filePath;
    innerAudioContext.obeyMuteSwitch = false;
    if (this.data.isPlaying) {
      innerAudioContext.stop();
      this.setData({ isPlaying: false });
    } else {
      innerAudioContext.play();
      this.setData({ isPlaying: true });
    }
    innerAudioContext.onEnded(() => {
      innerAudioContext.stop();
      this.setData({ isPlaying: false });
    });
  },
  startRecording: function() {
    wx.authorize({
      scope: 'scope.record',
      success: () => {
        clearInterval(interval);
        recorderManager.onStart(() => {
          console.log('recorder start');
          this.setData({ status: 1, showRecordingBar: false });
        });

        recorderManager.onStop((res) => {
          console.log('recorder stop', res);
          this.setData({
            'recordingData.filePath': res.tempFilePath,
            status: 3,
            showRecordingBar: true
          });
          this.recordingTimer(this.data.time);
        });

        const options = {
          duration: this.data.duration,
          sampleRate: 16000,
          numberOfChannels: 1,
          encodeBitRate: 96000,
          format: 'mp3',
          frameSize: 50,
        };
        this.recordingTimer();
        recorderManager.start(options);
      }
    });
  },
  stopRecording:function() {
    recorderManager.stop();
    this.recordingTimer(this.data.time);
  },
  playRecording: function() {
    innerAudioContext.src = this.data.recordingData.filePath;
    innerAudioContext.obeyMuteSwitch = false;

    if (this.data.playStatus == 0) {
      this.setData({ playStatus: 1 });
      innerAudioContext.play();
    }

    innerAudioContext.onEnded(() => {
      innerAudioContext.stop();
      this.setData({ playStatus: 0 });
    });
  },
  recordingTimer: function(time) {
    if (time == undefined) {
      interval = setInterval(() => {
        this.setData({ time: this.data.time + 1 });
      }, 1000);
    } else {
      clearInterval(interval);
      console.log("暂停计时");
    }
  },
  resetRecording: function() {
    wx.showModal({
      title: "重新录音",
      content: "是否重新录制?",
      success: (res) => {
        if (res.confirm) {
          this.setData({ time: 0, 'recordingData.filePath': "", status: 0, playStatus: 0, showRecordingBar: false });
          innerAudioContext.stop();
        }
      }
    });
  },
  toggleRecordingLayout:function() {
    this.setData({ showRecordingLayout: !this.data.showRecordingLayout });
  },

  hideRecordingLayout: function() {
    this.setData({ showRecordingLayout: false });
  },

  onRecordingComplete(res) {
    this.setData({
      recordingData: {
        filePath: res.tempFilePath
      },
      audioPath: res.tempFilePath
    });
  },
})